<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2024-10-17 11:57:58
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-08-03 12:54:06
 * @Description: 
 * 
 * Copyright (c) 2024 by xiaoMing.Cao, All Rights Reserved. 
-->
<template>
  <div class="upload-container">
    <el-upload action="https://up-z2.qiniup.com" class="avatar-uploader" :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :data="uploadData">
      <div v-if="props.imageUrl" class="image-preview-container">
        <img :src="props.imageUrl" class="avatar" @click="previewImage" />
        <div class="image-actions">
          <el-button type="danger" size="small" circle @click.stop="deleteImage" class="delete-btn">
            <el-icon color="#333"><Delete /></el-icon>
          </el-button>
        </div>
      </div>
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="600px" center>
      <div class="preview-content">
        <img :src="props.imageUrl" class="preview-image" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewVisible = false">关闭</el-button>
          <el-button type="danger" @click="deleteImage">删除图片</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { onMounted, ref, reactive } from 'vue';
  import { getQiniuToken } from '@/api/qiniu';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Delete, Plus } from '@element-plus/icons-vue';

  const emit = defineEmits(['success', 'delete']);
  const uploadData = reactive({
    key: '',
    token: '',
    imageSrc: ''
  });

  const previewVisible = ref(false);

  // 获取传入的图片路径
  const props = defineProps({
    imageUrl: {
      type: String,
      default: ''
    }
  });

  // 预览图片
  const previewImage = () => {
    if (props.imageUrl) {
      previewVisible.value = true;
    }
  };

  // 删除图片
  const deleteImage = async () => {
    try {
      await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });

      // 关闭预览弹窗
      previewVisible.value = false;

      // 触发删除事件
      emit('delete');

      ElMessage.success('图片已删除');
    } catch (error) {
      // 用户取消删除
    }
  };

  //款式图片 上传成功回调
  const handleUploadSuccess = res => {
    if (res.key) {
      uploadData.imageSrc = 'https://cdn.stite.net/' + res.key; // https://xxxx.com 为回显图片的地址，在七牛上配置的映射地址
      // emit成功出去
      emit('success', uploadData.imageSrc);
    } else {
      ElMessage({
        type: 'error',
        message: res.msg
      });
    }
  };

  onMounted(async () => {
    const res = await getQiniuToken();
    if (res.code == 200) {
      uploadData.token = res.data.uploadToken;
    } else {
      ElMessage.error('获取七牛云token失败，请稍后重试');
    }
  });

  const beforeUpload = async file => {
    try {
      // 通过请求后端获取七牛token
      // const res = await getQiniuToken();
      // if (res.code == 200) {
      uploadData.key = `plp/${file.uid}${file.name}`;
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isGIF = file.type === 'image/gif';

      if (!isJPG && !isPNG && !isGIF) {
        ElMessage.error('上传图片只能是 JPG/JPEG/PNG 格式!');
        return Promise.reject();
      }

      return isJPG || isPNG || isGIF;
    } catch (error) {
      console.log(error);
      ElMessage.error('上传失败');
    }
  };
</script>

<style scoped lang="scss">
  .upload-container {
    position: relative;
  }

  .avatar-uploader .avatar {
    width: 88px;
    height: 88px;
    display: block;
    cursor: pointer;
    transition: opacity 0.3s;

    &:hover {
      opacity: 0.8;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #dfdfdf;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 88px;
    height: 88px;
    text-align: center;
    border: 1px dashed #dfdfdf;
    border-radius: 8px;
  }

  .image-preview-container {
    position: relative;
    display: inline-block;

    &:hover .image-actions {
      opacity: 1;
    }
  }

  .image-actions {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
  }

  .delete-btn {
    background: rgba(255, 255, 255, 0.9);
    border: none;

    &:hover {
      background: #fff;
    }
  }

  .preview-content {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .preview-image {
    max-width: 100%;
    max-height: 400px;
    object-fit: contain;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
